﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

namespace Directory.Web
{
	public partial class Admin_LogoUpload : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			string absolutePath = Server.MapPath(GetFullPath());
			string sucessFiles = string.Empty;
			string failedFiles = string.Empty;
			for (int i = 0; i < Request.Files.Count; i++)
			{
				HttpPostedFile file = Request.Files[i];
				if (!string.IsNullOrEmpty(file.FileName))
				{
					string fileName = file.FileName;//FF上传文件时，文件名不包括路径；

					try
					{
						fileName = file.FileName.Substring(file.FileName.LastIndexOf("\\"));//IE上传文件时，文件名为文件的完整路径；
					}
					catch { }

					try
					{
						file.SaveAs(absolutePath + "\\" + fileName);
						sucessFiles += fileName + ";";
					}
					catch
					{
						failedFiles += fileName + ";";
					}
				}
			}
			if (!string.IsNullOrEmpty(sucessFiles))
			{
				if (string.IsNullOrEmpty(failedFiles))
				{
					Page.ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('上传成功:" + sucessFiles + "');try{window.opener.location.reload();window.close();}catch(ex){top.location.reload();}</script>");
				}
				else
				{
					Page.ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('上传成功:" + sucessFiles + ";上传失败:" + failedFiles + "');try{window.opener.location.reload();window.close();}catch(ex){top.location.reload();}</script>");
				}
			}
			else if (!string.IsNullOrEmpty(failedFiles))
			{
				Page.ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('上传失败:" + failedFiles + "')</script>");
			}
			else { }
		}

		private string GetFullPath()
		{
			string basePath = string.Empty;
			try
			{
				basePath = ConfigurationManager.AppSettings["LogoBasePath"].Trim();
			}
			catch
			{
				try
				{
					basePath = Session["FileBasePath"].ToString().Trim();
				}
				catch
				{
					try
					{
						basePath = Server.HtmlDecode(Request.QueryString["LogoBasePath"].Trim());
					}
					catch { }
				}
			}

			string currentPath = string.Empty;
			try
			{
				currentPath = Server.HtmlDecode(Request.QueryString["CurrentPath"].Trim());
			}
			catch
			{
				try
				{
					currentPath = Session["CurrentPath"].ToString().Trim();
				}
				catch { }
			}

			if (!basePath.EndsWith("/") && !string.IsNullOrEmpty(basePath))
			{
				basePath += "/";
			}

			string fullPath = basePath + currentPath;
			while (fullPath.IndexOf("//") > 0)
			{
				fullPath = fullPath.Replace("//", "/");
			}
			return fullPath;
		}
	}
}